/*
 * @Date: 2023-11-14 09:28:10
 * @LastEditors: lyx
 * @LastEditTime: 2023-11-14 16:12:39
 * @FilePath: \sup-mimi-program-server\utils\mongo-crud\index.ts
 * @Description:
 */
import { Model } from 'mongoose';

import { get } from 'lodash';
export const isQueryAll = (page = 1, limit = 10) => {
  return page === 0 && limit === 0;
};

/**
 * @description: 接口参数获取分页信息
 * @param {ICrudBody} params
 * @return {*}
 */
export const getMongoQueryParams = async (
  params: ICrudBody,
  modal: Model<{} | any>,
): Promise<ICrudQuery> => {
  let [page, limit] = get(params, 'requestBase.page', '1-10')
    ?.split('-')
    .map((item) => parseInt(item)) ?? [1, 10];
  const where = get(params, 'data.where', {});
  let skip = get(params, 'requestBase.skip', 0);
  const populate = get(params, 'requestBase.populate', undefined);
  const sort = get(params, 'requestBase.sort', undefined);
  const collation = get(params, 'requestBase.collation', undefined);

  if (skip < 1) {
    skip = (page - 1) * limit;
  }

  const total = await modal.countDocuments(where);
  if (isQueryAll(page, limit)) {
    // 兼容 0-0 查询所有
    skip = 0;
    limit = total;
    page = 1;
  }
  return {
    page,
    limit,
    where,
    skip,
    populate,
    sort,
    collation,
    total,
  };
};
